package org.rsbot.script.webwalking;

import java.awt.Cursor;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

import org.rsbot.script.webwalking.MapGraph.PicInfo;
import org.rsbot.script.webwalking.MapGraph.XY;

/**
 * @author WebWalker
 * 
 *         Panel used for image and calculations
 */
public class MapLabel extends JLabel {
	/**
	 * 
	 */
	private static final long serialVersionUID = -2338111133506110463L;
	private final URL imageURL;
	private Point hoveredPoint = null;
	private Point clickedPoint = null;
	private double pixelsPerTileH;
	private double pixelsPerTileW;

	MapLabel(URL picURL) {
		this.imageURL = picURL;
	}

	public void setIcon() {
		setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
		setIcon(new ImageIcon(imageURL));
	}

	static StringSelection st = new StringSelection("");
	static ClipboardOwner c = new ClipboardOwner() {
		@Override
		public void lostOwnership(Clipboard clipboard, Transferable contents) {
		}
	};

	public XY getHoveringTile(PicInfo PI) throws InterruptedException {
		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				clickedPoint = arg0.getPoint();
			}
		});
		pixelsPerTileH = (PI.dimensions.y / (PI.originTile.y - PI.northTile.y));
		pixelsPerTileW = (PI.dimensions.x / (PI.eastTile.x - PI.northTile.x));
		hoveredPoint = getMousePosition();
		if (clickedPoint != null) {
			XY clicked = new XY((int) Math.nextUp(PI.northTile.x
					+ (clickedPoint.getX() / pixelsPerTileW)),
					(int) Math.nextUp(PI.northTile.y
							+ (clickedPoint.getY() / pixelsPerTileH)));
			st = new StringSelection("new RSTile(" + (int) clicked.x + ", "
					+ (int) clicked.y + ");");
			Toolkit.getDefaultToolkit().getSystemClipboard().setContents(st, c);
			clickedPoint = null;
		}
		if (hoveredPoint != null)
			return new XY((int) Math.nextUp(PI.northTile.x
					+ (hoveredPoint.getX() / pixelsPerTileW)),
					(int) Math.nextUp(PI.northTile.y
							+ (hoveredPoint.getY() / pixelsPerTileH)));
		else
			return new XY(0, 0);
	}
}